const cloud = require('wx-server-sdk')

cloud.init()

const SUCCESS = 0;
const BAD_PARAM = -1;
const NOT_FOUND = -2;

/// (id: UserId, content: User) => (code: StatusCode)
exports.main = async (event) => {
  const id = event.id;
  const content = event.content;
  
  if (id == null || content == null) {
    return {
      code: BAD_PARAM
    };
  }

  let parsedContent;

  try {
    parsedContent = JSON.parse(content);
  } catch (e) {
    return {
      code: BAD_PARAM
    };
  }

  const db = cloud.database();
  try {
    await db.collection('users').doc(id).update({
      data: parsedContent
    });
    return {
      code: SUCCESS
    };
  } catch (e) {
    return {
      code: NOT_FOUND
    };
  }
}
